package com.uzai.console.service.mini.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.enums.mini.MiniTradeStatus;
import com.uzai.common.enums.mini.MiniTradeType;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.dto.mini.minitrade.MiniTradeQuery;
import com.uzai.console.entity.MiniTrade;
import com.uzai.console.mapper.MiniTradeMapper;
import com.uzai.console.service.mini.MiniTradeService;
import com.uzai.console.service.mini.MiniTradeSyncService;
import com.uzai.console.service.ratelimit.RatelimitService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author liuqi
 * @date 2021年08月25日 20:17
 */
@Service
public class MiniTradeSyncServiceImpl implements MiniTradeSyncService {

    Logger logger = LoggerFactory.getLogger(MiniTradeSyncServiceImpl.class);

    @Autowired
    private MiniTradeMapper miniTradeMapper;
    @Autowired
    private RatelimitService ratelimitService;
    @Autowired
    private MiniTradeService miniTradeService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 小程序交易查询
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param
     * @return null
     */
    @Async("taskExecutor")
    public void miniTradeQuery(){

        //限流key
        String taskLimitKet = "-miniTradeQuery-taskLimitKey-";
        Object object = redisTemplate.opsForValue().get(taskLimitKet);
        if(object != null){
            return;
        }
        //保存限流key
        redisTemplate.opsForValue().set(taskLimitKet, taskLimitKet, 30, TimeUnit.MINUTES);

        logger.info("-----调用小程序交易查询支付结果线程--xxlJob start--");

        try{

            Integer now = DateUtil.getNowTime();
            MiniTradeQuery miniTradeQuery = new MiniTradeQuery();
            miniTradeQuery.setStatus(MiniTradeStatus.TRADING.getCode()); //付款中
            miniTradeQuery.setType(MiniTradeType.REFUND.getCode());     //只处理退款

            //查询所有的支付宝支付记录
            Page<MiniTrade> page = new Page<>();
            page.setCurrent(1);//只查第一页
            page.setSize(10); //每页查询10个
            page.addOrder(OrderItem.asc("id"));//默认id升序
            Long idStart = 0L;
            List<MiniTrade> miniTradeList = miniTradeMapper.findByList(page, miniTradeQuery);
            while (miniTradeList != null && miniTradeList.size() > 0){
                for (MiniTrade miniTrade : miniTradeList){
                    try{
                        if(miniTrade.getId().longValue() > idStart.longValue()){
                            idStart = miniTrade.getId();
                        }
                        //限流判断
                        boolean inRateLimit = ratelimitService.inRateLimit("miniTradeQuery-" + miniTrade.getId(),1,10);
                        if (!inRateLimit){
                            //logger.info("--inRateLimit false. tradeno={}",alipayDetail.getTradeno());
                            continue;
                        }
                        miniTradeService.miniTradeQueryState(miniTrade);
                    }catch (Exception e){
                        logger.error("--调用小程序交易查询支付结果线程失败-{}", e);
                    }
                }

                miniTradeQuery.setIdStart(idStart);
                miniTradeList = miniTradeMapper.findByList(page, miniTradeQuery);
            }

        }catch (Exception e){
            logger.info(e.getMessage());
        }finally {
            //删除限流key
            redisTemplate.delete(taskLimitKet);
        }
    }

}
